package com.example.lock;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/***
 *
 * 基于zk实现分布式锁。 需要zk支持，整合成本较高
 */
public class ZkLock implements Lock {

    Logger logger = LoggerFactory.getLogger(getClass());

    private CuratorFramework curatorFramework;

    private String path;

    private InterProcessMutex interProcessMutex;

    @Override
    public void lock() throws Exception {
        this.interProcessMutex = new InterProcessMutex(this.curatorFramework, this.path);
        this.interProcessMutex.acquire();
    }

    @Override
    public void unlock() throws Exception {
        if (this.interProcessMutex != null && this.interProcessMutex.isAcquiredInThisProcess()) {
            this.interProcessMutex.release();
        }
    }

    public ZkLock(CuratorFramework curatorFramework, String path) {
        this.curatorFramework = curatorFramework;
        this.path = path;
    }

    public CuratorFramework getCuratorFramework() {
        return curatorFramework;
    }

    public void setCuratorFramework(CuratorFramework curatorFramework) {
        this.curatorFramework = curatorFramework;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public InterProcessMutex getInterProcessMutex() {
        return interProcessMutex;
    }

    public void setInterProcessMutex(InterProcessMutex interProcessMutex) {
        this.interProcessMutex = interProcessMutex;
    }
}
